<template>
  <div class="flex">
    <div class="form-control">
      <input type="file" ref="fileInput" @change="handleFileChange" class="hidden"/>
      <label class="label">
        <button class="btn btn-neutral btn-outline btn-sm"
                @click="triggerFileUpload">上传文件
        </button>
      </label>
      <div class="w-full h-4"></div>
      <div class="flex" v-if="modelValue">
        <div class="flex justify-center items-center gap-4 py-2">
          <a target="_blank" class="font-semibold text-sm hover:text-green-500" :href="genFileUrl(modelValue)">{{modelValue}}</a>
          <svg xmlns="http://www.w3.org/2000/svg" @click="deleteFile()" viewBox="0 0 16 16" fill="currentColor" class="size-4 cursor-pointer hover:text-rose-600">
            <path fill-rule="evenodd" d="M5 3.25V4H2.75a.75.75 0 0 0 0 1.5h.3l.815 8.15A1.5 1.5 0 0 0 5.357 15h5.285a1.5 1.5 0 0 0 1.493-1.35l.815-8.15h.3a.75.75 0 0 0 0-1.5H11v-.75A2.25 2.25 0 0 0 8.75 1h-1.5A2.25 2.25 0 0 0 5 3.25Zm2.25-.75a.75.75 0 0 0-.75.75V4h3v-.75a.75.75 0 0 0-.75-.75h-1.5ZM6.05 6a.75.75 0 0 1 .787.713l.275 5.5a.75.75 0 0 1-1.498.075l-.275-5.5A.75.75 0 0 1 6.05 6Zm3.9 0a.75.75 0 0 1 .712.787l-.275 5.5a.75.75 0 0 1-1.498-.075l.275-5.5a.75.75 0 0 1 .786-.711Z" clip-rule="evenodd" />
          </svg>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import {notificationError, notificationSuccess} from "~/utils/notification/index.js";
import {postForm, genFileUrl} from "~/utils/http/http-helper.js";

const props = defineProps({
  modelValue: String,
})

const emit = defineEmits(['update:modelValue'])

const fileInput = ref()
/**
 * 弹出文件选择框
 */
function triggerFileUpload() {
  fileInput.value.click(); // 模拟用户点击文件输入
}
// 处理文件改变
function handleFileChange(event) {
  console.log('files----')
  console.log(event.target.files)
  console.log('files----')
  const file = event.target.files[0]; // 获取文件
  if (file) {
    // 执行文件上传操作
    uploadImg(file);
  }
}
// 上传文件的方法
function uploadImg(file) {
  // 这里可以添加上传文件的逻辑，比如使用 FormData 发送请求等
  console.log('Uploading img...', file);
  // 上传文件的代码...
  const formData = new FormData();
  const filename = file.name
  formData.append('file', file);
  postForm('/api/files', formData).then(resp => {
    if (resp.success) {
      const data = resp.data
      emit('update:modelValue', data.key)
      console.log('上传文件...')
      console.log(data)
      console.log('------')
      console.log(data.key)
      console.log('上传文件...')

      notificationSuccess('上传文件成功')
    }
  }).catch(err => {
    console.log('err -> ' + err)
    notificationError(err)
  })
}
function deleteFile(){
  emit('update:modelValue', '')
}
</script>

<style scoped>

</style>